﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Reflection.Emit;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace LightORM.Core.Data
{

    internal sealed class DynamicBuilder<T>
    {
        #region log4net
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("DynamicBuilder");
        #endregion

        private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new Type[] { typeof(int) });
        private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new Type[] { typeof(int) });
        private delegate T Load(IDataRecord dataRecord);
        private delegate object GetValue(T t_Model);
        private delegate T SetValue(T t_Model, object value);
        private Load handler;

        private DynamicBuilder() { }

        public T BuildEntity(IDataRecord dataRecord)
        {
            return handler(dataRecord);
        }

        /// <summary>
        /// http://www.codeproject.com/KB/database/DynamicMethod_ILGenerator.aspx
        /// </summary>
        /// <param name="dataRecord"></param>
        /// <returns></returns>
        public static DynamicBuilder<T> CreateEntityBuilder(IDataRecord dataRecord)
        {
            Type t = typeof(T);
            DynamicBuilder<T> dynamicBuilder = new DynamicBuilder<T>();

            try
            {
                DynamicMethod method = new DynamicMethod("DynamicModelCreate", typeof(T), new Type[] { typeof(IDataRecord) }, typeof(T), true);

                ILGenerator generator = method.GetILGenerator();

                LocalBuilder result = generator.DeclareLocal(typeof(T));

                generator.Emit(OpCodes.Newobj, t.GetConstructor(Type.EmptyTypes));

                generator.Emit(OpCodes.Stloc, result);

                for (int i = 0; i < dataRecord.FieldCount; i++)
                {

                    PropertyInfo propertyInfo = t.GetProperty(dataRecord.GetName(i));
                    LocalBuilder il_P = generator.DeclareLocal(typeof(PropertyInfo));

                    Label endIfLabel = generator.DefineLabel();
                    if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
                    {
                        generator.Emit(OpCodes.Ldarg_0);
                        generator.Emit(OpCodes.Ldc_I4, i);
                        generator.Emit(OpCodes.Callvirt, isDBNullMethod);
                        generator.Emit(OpCodes.Brtrue, endIfLabel);

                        generator.Emit(OpCodes.Ldloc, result);
                        generator.Emit(OpCodes.Ldarg_0);
                        generator.Emit(OpCodes.Ldc_I4, i);
                        generator.Emit(OpCodes.Callvirt, getValueMethod);
                        generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i));
                        generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());

                        generator.MarkLabel(endIfLabel);
                    }
                }

                generator.Emit(OpCodes.Ldloc, result);
                generator.Emit(OpCodes.Ret);

                dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load));
            }
            catch (Exception ex)
            {
                log.Error("CreateEntityBuilder", ex);
            }
            return dynamicBuilder;
        }

    }
}
